package org.kernely.stream.utils;

import java.util.HashSet;
import java.util.Set;

import org.kernely.security.persistence.User;
import org.kernely.stream.StreamBundle;
import org.kernely.stream.dao.MessageDAO;
import org.kernely.stream.persistence.Message;
import org.kernely.ui.utils.KernelyNotification;

import com.vaadin.terminal.ExternalResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.themes.Reindeer;


/**
 * Extension of Button class to create a specific behavior about favorites
 */
public class FavButton extends Button{
	private boolean isFavorite = false;

	/**
	 * Default constructor
	 * @param message The message concerned by this button.
	 */
	public FavButton(final Message message){

		super();
		User current = StreamBundle.getSecurityService().getCurrentUser();
		for (User u : message.getFavoriteUsers()){
			if (u.equals(current)){
				isFavorite = true;
			}
		}
		if (isFavorite){
			this.setIcon(new ExternalResource("streambundle/images/fav_16*16.png"));
		} else {
			this.setIcon(new ExternalResource("streambundle/images/unfav_16*16.png"));
		}
		this.setStyleName(Reindeer.BUTTON_LINK);
		this.setSizeUndefined();
		this.addListener(new ClickListener() {

			/**
			 * Action called when the button is clicked.
			 */
			public void buttonClick(ClickEvent event) {
				// Update the concerned messsage
				Message m = MessageDAO.getInstance().findMessageById(message.getId());

				// Check if the message still exists
				if (m != null){
					Set<User> users = m.getFavoriteUsers();
					if (users == null){
						users = new HashSet<User>();
					}
					if (isFavorite){
						// The message is no longer considered as a favorite
						users.remove(StreamBundle.getSecurityService().getCurrentUser());
						setIcon(new ExternalResource("streambundle/images/unfav_16*16.png"));
						isFavorite = false;
					} else {
						// The message is now considered as a favorite
						users.add(StreamBundle.getSecurityService().getCurrentUser());
						setIcon(new ExternalResource("streambundle/images/fav_16*16.png"));
						isFavorite = true;
					}
					m.setFavoriteUsers(users);
					MessageDAO.getInstance().updateMessage(m);
				}
			}
		});
	}
}